import { useState, useEffect, type ChangeEvent } from 'react'
import { useNavigate } from 'react-router-dom'
import { useAuth } from '../contexts/AuthContext'

// 定义Prompt类型
interface Prompt {
  id: number
  title: string
  description: string
  prompt: string
  category: string
  aiModel: string
  author: string
  likes: number
  createdAt: string
  isCollected?: boolean
}

export default function HomePage() {
  const navigate = useNavigate()
  const { token, isAuthenticated } = useAuth()
  const [searchTerm, setSearchTerm] = useState('')
  const [prompts, setPrompts] = useState<Prompt[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')
  const [copiedId, setCopiedId] = useState<number | null>(null)
  const [collectingId, setCollectingId] = useState<number | null>(null)

  // 复制到剪贴板函数
  const copyToClipboard = async (text: string, promptId: number) => {
    try {
      await navigator.clipboard.writeText(text)
      setCopiedId(promptId)
      // 2秒后重置状态
      setTimeout(() => setCopiedId(null), 2000)
    } catch (err) {
      console.error('复制失败:', err)
      // 降级方案
      const textArea = document.createElement('textarea')
      textArea.value = text
      document.body.appendChild(textArea)
      textArea.select()
      document.execCommand('copy')
      document.body.removeChild(textArea)
      setCopiedId(promptId)
      setTimeout(() => setCopiedId(null), 2000)
    }
  }

  // 收藏/取消收藏函数
  const toggleCollect = async (promptId: number, isCurrentlyCollected: boolean) => {
    try {
      setCollectingId(promptId)
      
      console.log('token', token)
      const url = `http://localhost:8080/api/v1/prompts/${promptId}/collect`
      const method = isCurrentlyCollected ? 'DELETE' : 'POST'
      
      const response = await fetch(url, {
        method,
        headers: {
          'Content-Type': 'application/json',
          ...(token && { 'Authorization': `Bearer ${token}` })
        }
      })
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }
      
      const data = await response.json()
      
      if (data.code === 1) {
        // 更新本地状态
        setPrompts(prevPrompts => 
          prevPrompts.map(prompt => 
            prompt.id === promptId 
              ? { ...prompt, isCollected: !isCurrentlyCollected }
              : prompt
          )
        )
      } else {
        throw new Error(data.error || '操作失败')
      }
    } catch (err) {
      console.error('收藏操作失败:', err)
      // 如果没有token，提示用户登录
      if (!isAuthenticated) {
        alert('请先登录后再进行收藏操作')
      } else {
        alert(err instanceof Error ? err.message : '收藏操作失败，请稍后重试')
      }
    } finally {
      setCollectingId(null)
    }
  }

  // API调用函数
  const fetchPrompts = async () => {
    try {
      setLoading(true)
      setError('')
      const response = await fetch('http://localhost:8080/api/v1/prompts?page=1&limit=9')
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }
      
      const data = await response.json()
      
      if (data.code === 1) {
        // 转换API数据格式以匹配现有UI
        const transformedPrompts = data.data.prompts?.map((prompt: any) => ({
          id: prompt.id,
          title: prompt.title,
          description: prompt.description,
          prompt: prompt.content,
          category: prompt.category?.name || '未分类',
          aiModel: prompt.ai_model?.name || '未知模型',
          author: prompt.user?.username || '匿名',
          likes: prompt.like_count || 0,
          createdAt: new Date(prompt.created_at).toLocaleDateString('zh-CN'),
          isCollected: prompt.is_collected || false
        })) || []
        
        setPrompts(transformedPrompts)
      } else {
        throw new Error(data.error || '获取数据失败')
      }
    } catch (err) {
      console.error('获取prompts失败:', err)
      setError(err instanceof Error ? err.message : '网络错误，请稍后重试')
      // 如果API调用失败，使用模拟数据作为降级方案
      setPrompts([
        {
          id: 1,
          title: "科幻城市风景",
          description: "生成未来科幻城市的壮观景象",
          prompt: "A futuristic cyberpunk cityscape at night, neon lights reflecting on wet streets, flying cars, towering skyscrapers with holographic advertisements, highly detailed, 8k resolution",
          category: "风景",
          aiModel: "Midjourney",
          author: "张三",
          likes: 128,
          createdAt: "2024-01-15",
          isCollected: false
        },
        {
          id: 2,
          title: "梦幻森林",
          description: "创造神秘梦幻的魔法森林场景",
          prompt: "Enchanted magical forest with glowing mushrooms, fairy lights, ancient trees with twisted branches, mystical fog, fantasy atmosphere, digital art style",
          category: "奇幻",
          aiModel: "DALL-E",
          author: "李四",
          likes: 95,
          createdAt: "2024-01-14",
          isCollected: false
        },
        {
          id: 3,
          title: "宇宙星云",
          description: "绚丽多彩的宇宙星云景象",
          prompt: "Colorful nebula in deep space, swirling cosmic dust, bright stars, purple and blue hues, astronomical photography style, ultra high resolution",
          category: "宇宙",
          aiModel: "Stable Diffusion",
          author: "王五",
          likes: 203,
          createdAt: "2024-01-13",
          isCollected: false
        }
      ])
    } finally {
      setLoading(false)
    }
  }

  // 组件挂载时获取数据
  useEffect(() => {
    fetchPrompts()
  }, [])

  const filteredPrompts = prompts.filter((prompt: Prompt) =>
    prompt.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
    prompt.description.toLowerCase().includes(searchTerm.toLowerCase()) ||
    prompt.category.toLowerCase().includes(searchTerm.toLowerCase())
  )

  const handleSearchChange = (e: ChangeEvent<HTMLInputElement>) => {
    setSearchTerm(e.target.value)
  }

  return (
    <div className="min-h-screen bg-background">
      {/* Hero Section */}
      <section className="py-20 text-center">
        <div className="container">
          <h1 className="text-4xl font-bold mb-4">AI Prompt Hub</h1>
          <p className="text-xl text-muted mb-8">发现和分享最优质的 AI 提示词</p>
          <div className="max-w-md mx-auto">
            <input
              type="text"
              placeholder="搜索 prompts..."
              value={searchTerm}
              onChange={handleSearchChange}
              className="input"
            />
          </div>
        </div>
      </section>

      {/* Prompts Grid */}
      <section className="py-12">
        <div className="container">
          {/* 错误提示 */}
          {error && (
            <div className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-6">
              <p>⚠️ {error}</p>
              <button 
                onClick={fetchPrompts}
                className="mt-2 px-4 py-2 bg-red-600 text-white rounded hover:bg-red-700"
              >
                重试
              </button>
            </div>
          )}
          
          {/* 加载状态 */}
          {loading ? (
            <div className="flex justify-center items-center py-12">
              <div className="text-center">
                <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary mx-auto mb-4"></div>
                <p className="text-muted">正在加载 prompts...</p>
              </div>
            </div>
          ) : (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3">
              {filteredPrompts.length === 0 ? (
                <div className="col-span-full text-center py-12">
                  <p className="text-muted text-lg">没有找到匹配的 prompts</p>
                </div>
              ) : (
                filteredPrompts.map((prompt: Prompt) => (
                  <div key={prompt.id} className="card transition-shadow">
                    <div className="card-header">
                      <div className="flex items-center justify-between">
                        <div className="flex items-center space-x-2">
                          <h3 className="card-title">{prompt.title}</h3>
                          <span className="card-description">
                            by {prompt.author}
                          </span>
                        </div>
                      </div>
                      <div className="flex flex-wrap gap-2 mt-2">
                        <span className="px-2 py-1 bg-primary-light text-sm rounded-full">
                          {prompt.category}
                        </span>
                        <span className="px-2 py-1 bg-secondary text-sm rounded-full">
                          {prompt.aiModel}
                        </span>
                      </div>
                    </div>
                    <div className="card-content">
                      <p className="text-muted text-sm mb-4">{prompt.description}</p>
                      <div className="bg-muted p-3 rounded-md mb-4">
                        <code className="text-sm font-mono">
                          {prompt.prompt.length > 100
                            ? `${prompt.prompt.substring(0, 100)}...`
                            : prompt.prompt}
                        </code>
                      </div>
                      <div className="flex items-center justify-between">
                        <div className="flex items-center space-x-4 text-sm text-muted">
                          <span>👍 {prompt.likes}</span>
                          <span>📅 {prompt.createdAt}</span>
                        </div>
                        <div className="flex space-x-2">
                          <button 
                            className={`btn btn-sm transition-all duration-200 ${
                              copiedId === prompt.id 
                                ? 'btn-success' 
                                : 'btn-outline'
                            }`}
                            onClick={() => copyToClipboard(prompt.prompt, prompt.id)}
                          >
                            {copiedId === prompt.id ? '已复制!' : '复制'}
                          </button>
                          <button 
                            className={`btn btn-sm transition-all duration-200 ${
                              prompt.isCollected 
                                ? 'btn-warning' 
                                : 'btn-outline'
                            } ${
                              collectingId === prompt.id ? 'loading' : ''
                            }`}
                            onClick={() => toggleCollect(prompt.id, prompt.isCollected || false)}
                            disabled={collectingId === prompt.id}
                          >
                            {collectingId === prompt.id 
                              ? '处理中...' 
                              : prompt.isCollected 
                                ? '已收藏' 
                                : '收藏'
                            }
                          </button>
                          <button 
                            className="btn btn-primary btn-sm"
                            onClick={() => navigate(`/prompt/${prompt.id}`)}
                          >
                            查看详情
                          </button>
                        </div>
                      </div>
                    </div>
                  </div>
                ))
              )}
            </div>
          )}
        </div>
      </section>

      {/* Footer */}
      <footer>
        <div className="container py-8">
          <div className="text-center text-muted">
            <p>&copy; 2024 AI Prompt Hub. All rights reserved.</p>
          </div>
        </div>
      </footer>
    </div>
  )
}